package cn.gov.msa.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import cn.gov.msa.dao.OrgMapper;
import cn.gov.msa.model.Org;
import cn.gov.msa.service.OrgService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class OrgServiceImpl implements OrgService{
	
	@Autowired
	private OrgMapper orgMapper;

	@Override
	@Transactional
	public List<Org> selectOrg(Org org) {
		return orgMapper.selectOrg(org);
	}
	
	@Override
	@Transactional
	public List<Map<String, Object>> selectAllOrg(Org org) {
		return orgMapper.selectAllOrg(org);
	}

	@Override
	@Transactional
	public List<Org> queryNextOrg(Org org) {
		return orgMapper.queryNextOrg(org);
	}
	
	@Override
	@Transactional
	public List<Org> selectFrequentlyOrg(String companyId) {
		return orgMapper.selectFrequentlyOrg(companyId);
	}
	
	@Override
	@Transactional
	public JSONObject getOrg(String orgCode) {
		JSONObject jsonOrg = new JSONObject();
		Org org = new Org();
		org.setOrgCode(orgCode);
		List<Org> orgList = orgMapper.selectOrg(org);
		if (orgList.size() > 0) {
			org = orgList.get(0);

			JSONArray porgArray = new JSONArray();
			JSONObject porg = new JSONObject();

			porg.put("id", org.getOrgCode());
			porg.put("name", org.getOrgName());
			porgArray.add(porg);

			org.setOrgCode("");
			org.setPorgCode(orgCode);
			if (org.getOrgLevel() == 1) {
				org.setOrgLevel(2);
			} else if (org.getOrgLevel() == 2) {
				org.setOrgLevel(4);
			} else if (org.getOrgLevel() == 4) {
				org.setOrgLevel(5);
			} else {
				return jsonOrg;
			}
			List<Org> porgList = orgMapper.selectOrg(org);

			Org tempOrg = new Org();
			for (Org po : porgList) {
				porg.put("id", po.getOrgCode());
				porg.put("name", po.getOrgName());
				// 搜索下级机构
				if(po.getOrgLevel() < 5){
					tempOrg.setOrgCode(po.getOrgCode());
					tempOrg.setOrgLevel(po.getOrgLevel());
//					if (!"000000".equals(org.getPorgCode())) {
//						tempOrg.setOrgLevel(5);
//					}
					List<Org> queryNextOrg = orgMapper.queryNextOrg(tempOrg);
					JSONObject childOrg = new JSONObject();
					JSONArray childOrgArray = new JSONArray();
					for (Org co : queryNextOrg) {
						childOrg.put("id", co.getOrgCode());
						childOrg.put("name", co.getOrgName());
						childOrgArray.add(childOrg);
					}
					porg.put("city", childOrgArray);
				}
				porgArray.add(porg);
			}
			jsonOrg.put("province", porgArray);
			jsonOrg.put("hot", new JSONArray());
		}
		return jsonOrg;
	}

	 
	@Override
	public Org selectBy4aOrgCode(String orgCode4A) {
		 
		return orgMapper.selectBy4aOrgCode(orgCode4A);
	}

}
